package cn.cc.ProviderAndConsumer;

class Resource{
    private int num ;//随机生成整数
    private int sum ;//累计求和
    boolean flag = true ;//flag为true表示可以进行生产，false表示可以进行消费，防止sum打印时产生线程安全问题
    public synchronized int generic() throws Exception{
        if(flag == false ){
            super.wait();
        }
        this.num = java.util.concurrent.ThreadLocalRandom.current().nextInt(10);
        System.err.println("生产者线程"+ Thread.currentThread().getName());
        System.err.println(num);
        super.notifyAll();
        this.flag = false ;
        return num;
    }
    public synchronized void print()throws Exception{
        if (flag == true) {
            super.wait();
        }
        System.err.println("消费者线程"+ Thread.currentThread().getName());
        sum += this.num ;

        System.err.println("sum = " + sum);
        this.flag = true ;
    }
}

class Provider implements Runnable{
    private Resource resource ;

    public Provider(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        try {
            this.resource.generic();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class Consumer implements Runnable{
    private Resource resource ;
    public Consumer(Resource resource) {
        this.resource = resource ;
    }
    @Override
    public void run() {
        try {
            this.resource.print();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        Resource resource = new Resource();
        for (int i = 0 ; i < 30; i ++){
            Thread.sleep(10);
            new Thread(new Provider(resource),"生产线程").start();
            new Thread(new Consumer(resource),"消费线程").start();
        }
    }
}
